<script setup>
import {post} from '../../config/Request.js'
import {ElMessage} from 'element-plus'
import {onMounted, ref} from "vue";
import api from "@/request/apis.js";
import ParamDefine from "@/views/restapi/ParamDefine.vue";
import ResultWrapper from "@/views/restapi/ResultWrapper.vue";
import HeaderConfig from "@/views/restapi/HeaderConfig.vue";
import {nanoid} from "nanoid";
import {Button, Tag} from "view-ui-plus";
import ProcessRelationConfig from "@/views/process/ProcessRelationConfig.vue";

onMounted(() => {
  queryApiList();
})
const addApiFlag = ref(false);

const apiModel = ref({});
const saveApi = async () => {
  await api.saveApiConfig(apiModel.value);
  addApiFlag.value = false;
  await queryApiList();
  apiModel.value = {};
}
const apiList = ref([]);
const queryApiList = async () => {
  const list = await api.apiList();
  apiList.value = list;
}

const apiDetailModel = ref({});

const renderRight = async (row) => {

  //先查一下
  const result = await api.queryApiById(row.id);

  const versions = await api.queryApiVersionList(row.id);

  if (versions) {
    versionList.value = [];
    versionList.value = versions;
  }
  if (!versionList.value) {
    versionList.value = [];
  }
  apiDetailModel.value = result;
  if (apiDetailModel.value.methods) {
    apiDetailModel.value.methods = JSON.parse(apiDetailModel.value.methods);
  }

  if (apiDetailModel.value.resultWrapperConfig) {
    const cb = JSON.parse(apiDetailModel.value.resultWrapperConfig);
    apiDetailModel.value.sourceFieldDefine = cb.sourceFieldDefine;
    apiDetailModel.value.targetFieldDefine = cb.targetFieldDefine;
  }
  if (!apiDetailModel.value.sourceFieldDefine) {
    apiDetailModel.value.sourceFieldDefine = {
      params: [],
      isArrayFlag: false,
      isViewBasicFieldFlag: false,
      isAddColumnFlag: false,
      isUpdateColumnFlag: false,
      isRemoveColumnFlag: false,
      isAddChildrenColumnFlag: false,
      isMappingColumnFlag: true,
      isViewArrayFlag: false,
      basicTypeFlag: false,
      basicFieldType: false
    }
  }


  if (!apiDetailModel.value.targetFieldDefine) {
    apiDetailModel.value.targetFieldDefine = {
      params: [],
      isArrayFlag: false,
      isViewBasicFieldFlag: false,
      isViewArrayFlag: false,
      isMappingColumnFlag: true,
      basicTypeFlag: false,
      basicFieldType: false
    }
  }

  if (!apiDetailModel.value.resultWrapperFlag) {
    apiDetailModel.value.resultWrapperFlag = false;
  }


  if (versionList.value.length <= 0) {
    return
  }

  for (const version of versionList.value) {
    initVersion(version);
  }

  activeVersion.value = versionList.value[0].apiVersion;
}

const initVersion = (version) => {
  if (!version.entity) {
    version.entity = {};
  } else {

    version.input = {};
    version.input.params = JSON.parse(version.entity.inputParam);
    version.input.isArrayFlag = version.entity.inputParamArrayFlag;
    version.input.basicTypeFlag = version.entity.inputParamBasicTypeFlag;
    version.input.basicFieldType = version.entity.inputBasicFieldType;

    version.output = {};
    version.output.params = JSON.parse(version.entity.resultParam);
    version.output.isArrayFlag = version.entity.resultParamArrayFlag;
    version.output.basicTypeFlag = version.entity.resultParamBasicTypeFlag;
    version.output.basicFieldType = version.entity.resultBasicFieldType;
  }

  // setDefaultValue();
  if (!version.input) {
    version.input = {
      isArrayFlag: false,
      basicTypeFlag: false,
      basicFieldType: null,
      params: []
    };
  }
  if (!version.output) {
    version.output = {
      isArrayFlag: false,
      basicTypeFlag: false,
      basicFieldType: null,
      params: []
    };
  }
}
const apiTypeCodeList = ref([
  {
    name: "REST",
    code: "REST"
  }
]);

const protocolTypeCodeList = ref([
  {
    name: "http",
    code: "http"
  }, {
    name: "https",
    code: "https"
  }
])

const methodList = ref([
  {
    name: "GET",
    code: "GET"
  }, {
    name: "POST",
    code: "POST"
  }, {
    name: "PUT",
    code: "PUT"
  }, {
    name: "OPTION",
    code: "OPTION"
  },
  {
    name: "DELETE",
    code: "DELETE"
  }
]);


const updateApi = () => {
  apiDetailModel.value.versionList = versionList.value;
  const params = JSON.parse(JSON.stringify(apiDetailModel.value));
  if (!params.id) {
    return
  }

  for (const cp of params.versionList) {

    if (cp.input) {
      if (cp.input.params) {
        cp.entity.inputParam = JSON.stringify(cp.input.params);
      }
      cp.entity.inputParamArrayFlag = cp.input.isArrayFlag;
      cp.entity.inputBasicFieldType = cp.input.basicFieldType;
      cp.entity.inputParamBasicTypeFlag = cp.input.basicTypeFlag;
    }
    if (cp.output) {
      if (cp.output.params) {
        cp.entity.resultParam = JSON.stringify(cp.output.params);
      }
      cp.entity.resultParamArrayFlag = cp.output.isArrayFlag;
      cp.entity.resultBasicFieldType = cp.output.basicFieldType;
      cp.entity.resultParamBasicTypeFlag = cp.output.basicTypeFlag;
    }
  }


  params.resultWrapperConfig = JSON.stringify({
    sourceFieldDefine: apiDetailModel.value.sourceFieldDefine,
    targetFieldDefine: apiDetailModel.value.targetFieldDefine
  });


  if (params.methods && params.methods.length > 0) {
    params.methods = JSON.stringify(params.methods)
  }
  api.updateApiById(params);
  // console.log(JSON.parse(JSON.stringify(apiDetailModel.value)))
}

const activeVersion = ref();
const versionList = ref([]);
const handleTabsEdit = (targetName, action) => {
  if (action === 'add') {
    const version = nanoid(5);
    const newTabName = `${version}`;
    const cb = {
      apiVersion: newTabName
    };
    initVersion(cb);
    versionList.value.push(cb)

    activeVersion.value = newTabName;
  } else if (action === 'remove') {
    const tabs = versionList.value
    let activeName = activeVersion.value
    if (activeName === targetName) {
      tabs.forEach((tab, index) => {
        if (tab.name === targetName) {
          const nextTab = tabs[index + 1] || tabs[index - 1]
          if (nextTab) {
            activeName = nextTab.name
          }
        }
      })
    }

    activeVersion.value = activeName
    versionList.value = tabs.filter((tab) => tab.name !== targetName)
  }
}

const offOnline = async (apiConfig) => {
  if (!apiConfig.apiStatusCode || apiConfig.apiStatusCode == 'OFFLINE') {
    await api.updateApiStatusCode(apiConfig.id, 'ONLINE');
  } else if (apiConfig.apiStatusCode == 'ONLINE') {
    await api.updateApiStatusCode(apiConfig.id, 'OFFLINE');
  }
  await queryApiList();
}

const setVersionLatest = async (apiVersion) => {

  if (!apiVersion.id) {
    return;
  }

  if (apiVersion.latestFlag) {
    await api.updateApiVersionLatestFlag(apiVersion.id, false);
    apiVersion.latestFlag = false;
  } else {
    await api.updateApiVersionLatestFlag(apiVersion.id, true);
    apiVersion.latestFlag = true;

    for (const v of versionList.value) {
      if (v.id == apiVersion.id) {
        continue
      }
      v.latestFlag = false;
    }
  }
}
const processRelationVisible = ref(false);
const bizId = ref();
const relationProcess = () => {
  if (!apiDetailModel.value.id) {
    return;
  }
  bizId.value = apiDetailModel.value.id;
  processRelationVisible.value = true;

}
</script>

<template>
  <div>

    <el-container>
      <el-aside width="300px" style="border: 1px solid #ccc;padding: 10px">
        <el-row style="margin-bottom: 10px;">
          <el-col :span="10">
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="addApiFlag=true">新增</el-button>
          </el-col>
          <el-col :span="2">
          </el-col>
          <el-col :span="4">
            <el-button type="primary">删除</el-button>
          </el-col>
        </el-row>

        <el-row v-for="api in apiList">
          <el-card class="box-card" style="width: 100%;">
            <template #header>
              <div class="card-header">
                <Tag @click="renderRight(api)">{{ api.apiName }}</Tag>
                &nbsp; &nbsp; &nbsp; &nbsp;<span>{{ api.apiCode }}</span>
              </div>
            </template>
            <div>
              {{ api.description }}
            </div>
            <template #footer>
              <Button :type="api.apiStatusCode == 'ONLINE' ? 'success' : 'dashed'" @click="offOnline(api)">{{
                  api.apiStatusCode == 'ONLINE' ? '下线' : '上线'
                }}
              </Button>
            </template>
          </el-card>
        </el-row>


        <el-dialog v-model="addApiFlag">
          <el-form :model="apiModel">
            <el-form-item label="api名称">
              <el-input v-model="apiModel.apiName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="api编码">
              <el-input v-model="apiModel.apiCode" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="api描述">
              <el-input v-model="apiModel.description" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="addApiFlag = false">取 消</el-button>
            <el-button type="primary" @click="saveApi">确 定</el-button>
          </div>
        </el-dialog>


      </el-aside>


      <el-main>

        <el-row justify="left" style="margin-top: 10px;">
          <el-col :span="5">
            <el-tag class="ml-2" type="success">{{ apiDetailModel.apiName }}</el-tag>
          </el-col>
          <el-col :span="5">
            <el-tag class="ml-2" type="info">{{ apiDetailModel.apiCode }}</el-tag>
          </el-col>
          <el-col :span="10">
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="relationProcess">关联流程</el-button>
            <el-dialog v-model="processRelationVisible" width="1000px">
              <ProcessRelationConfig :biz-id="bizId" biz-type="API"></ProcessRelationConfig>
            </el-dialog>

          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="updateApi">保存</el-button>
          </el-col>
        </el-row>
        <el-row justify="left" style="margin-top: 10px;">
          <el-col :span="24">
            <hr/>
          </el-col>
        </el-row>

        <el-row justify="start" style="margin-top: 10px;">
          <el-col :span="24">
            <el-tag class="ml-2" type="success">{{ apiDetailModel.description }}</el-tag>
          </el-col>
        </el-row>

        <el-row justify="left" style="margin-top: 10px;">
          <el-col :span="24">
            <hr/>
          </el-col>
        </el-row>
        <el-row justify="start" style="margin-top: 10px">
          <el-col :span="2">
            api类型：
          </el-col>
          <el-col :span="5">
            <el-select
                v-model="apiDetailModel.apiTypeCode"
                class="m-2"
                placeholder="Select"
                size="large"
            >
              <el-option
                  v-for="item in apiTypeCodeList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
              />
            </el-select>
          </el-col>

          <el-col :span="2">
            协议类型：
          </el-col>
          <el-col :span="5">
            <el-select
                v-model="apiDetailModel.protocolTypeCode"
                class="m-2"
                placeholder="Select"
                size="large"
            >
              <el-option
                  v-for="item in protocolTypeCodeList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
              />
            </el-select>
          </el-col>

          <el-col :span="2">
            method：
          </el-col>
          <el-col :span="5">
            <el-select
                v-model="apiDetailModel.methods"
                class="m-2"
                multiple
                placeholder="Select"
                size="large"
            >
              <el-option
                  v-for="item in methodList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
              />
            </el-select>
          </el-col>
        </el-row>
        <el-row justify="left" style="margin-top: 10px;">
          <el-col :span="24">
            <hr/>
          </el-col>
        </el-row>

        <el-row justify="start" style="margin-top: 10px">
          <el-col :span="3">
            host：
          </el-col>

          <el-col :span="4">
            <el-input v-model="apiDetailModel.host" placeholder="请输入host"></el-input>
          </el-col>

          <el-col :span="3">
            contextPath：
          </el-col>

          <el-col :span="5">
            <el-input v-model="apiDetailModel.contextPath" placeholder="请输入contextPath"></el-input>
          </el-col>
          <el-col :span="3">
            path：
          </el-col>

          <el-col :span="5">
            <el-input v-model="apiDetailModel.path" placeholder="请输入path"></el-input>
          </el-col>
        </el-row>
        <el-row justify="left" style="margin-top: 10px;">
          <el-col :span="24">
            <hr/>
          </el-col>
        </el-row>


        <el-row justify="start" style="margin-top: 10px">
          <el-col :span="24">
            <el-tabs v-model="activeVersion" type="card" editable @edit="handleTabsEdit" class="demo-tabs">
              <el-tab-pane v-for="version in versionList" :label="version.apiVersion" :name="version.apiVersion">
                <template #label>
                      <span class="custom-tabs-label">

                        <span>{{ version.apiVersion }}</span>
                        &nbsp;   &nbsp;   &nbsp;
                        <Button type="success" @click="setVersionLatest(version)" size="small"
                                shape="circle">{{ version.latestFlag ? 'unlatest' : 'latest' }}</Button>
                      </span>
                </template>
                <el-row justify="start" style="margin-top: 10px">
                  <el-col :span="1">
                    <el-tag class="ml-2" type="success">headers</el-tag>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <HeaderConfig :params="version"></HeaderConfig>
                  </el-col>
                </el-row>
                <el-row justify="left" style="margin-top: 10px;">
                  <el-col :span="24">
                    <hr/>
                  </el-col>
                </el-row>

                <el-row justify="start" style="margin-top: 10px">
                  <el-col :span="1">
                    <el-tag class="ml-2" type="success">参数</el-tag>
                  </el-col>
                </el-row>


                <el-row justify="start" style="margin-top: 10px">
                  <el-col :span="12">
                    <el-row justify="start" style="margin-top: 10px">
                      <el-col :span="2">
                        <el-tag class="ml-2" type="success">input</el-tag>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <ParamDefine :params="version.input" :isViewBasicFieldFlag="true"
                                     :isViewArrayFlag="true"></ParamDefine>
                      </el-col>
                    </el-row>

                  </el-col>

                  <el-col :span="12">
                    <el-row justify="start" style="margin-top: 10px">
                      <el-col :span="2">
                        <el-tag class="ml-2" type="success">output</el-tag>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="24">
                        <ParamDefine :params="version.output" :isViewBasicFieldFlag="true"
                                     :isViewArrayFlag="true"></ParamDefine>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>

              </el-tab-pane>
            </el-tabs>


          </el-col>
        </el-row>


        <el-row justify="left" style="margin-top: 10px;">
          <el-col :span="24">
            <hr/>
          </el-col>
        </el-row>

        <el-row justify="start" style="margin-top: 10px">
          <el-col :span="1">
            <el-tag class="ml-2" type="success">resultWrapper</el-tag>
          </el-col>
        </el-row>


        <el-row justify="start" style="margin-top: 10px">
          <el-col :span="24">
            <ResultWrapper :entity="apiDetailModel"></ResultWrapper>
          </el-col>
        </el-row>


      </el-main>
    </el-container>

  </div>
</template>

<style scoped>

</style>